<?php
    /**
     * Created by PhpStorm.
     * User: huangzhongwei
     * Date: 2018/11/17
     * Time: 16:44
     */

    namespace app\api\service;

    use app\common\model\Order;
    use app\lib\exception\MissException;
    use app\api\service\Order as OrderServer;
    use app\lib\exception\RefundException;
    use app\lib\exception\SuccessMessage;
    use app\lib\exception\TokenException;
    use think\Exception;
    use think\facade\Env;
    use app\common\model\Refund as RefundModel;
    use think\facade\Log;


    require_once(Env::get('extend_path') . '/NewWxPay/WxPay.Api.php');
    require_once(Env::get('extend_path') . '/NewWxPay/WxPay.Config.php');

    class Refund
    {
        private $orderNo;//商户订单号
        private $outRefundNo;//退款订单号
        private $totalFee;//订单价格
        private $refundFee;//退款金额
        private $opUserId;
        private $orderID;
        private $config;


        /**
         * 获取orderID;
         *
         * @param $orderID
         *
         * @throws Exception
         */
        function __construct($orderID)
        {
            if (!$orderID) {
                throw new Exception('订单号不允许为NULL');
            }
            $this->orderID = $orderID;
            $this->config  = new \WxPayConfig();
        }


        public function refund()
        {
            //只能退款申请中的订单才能退款

            $order = (new Order())->where('state', 7)->get($this->orderID);
            if (!$order) {
                throw new MissException(['msg' => '当前订单不合法', 'errorCode' => 60006]);
            }

            $this->orderNo = $order['order_no'];

            $this->outRefundNo = OrderServer::makeOrderNo();

            $this->totalFee = $order['order_price'] * 100;

            $this->refundFee = $order['order_price'] * 100;

            $this->opUserId = $this->config->GetMerchantId();

            return $this->makeWxRefundInfo();

        }

        private function makeWxRefundInfo()
        {
//            $openid = Token::getCurrentTokenVar('openid');
//            if (!$openid) {
//                throw new TokenException();
//            }

            $wxRefundData = new \WxPayRefund();

            $wxRefundData->SetOut_trade_no($this->orderNo);

            $wxRefundData->SetOut_refund_no($this->outRefundNo);

            $wxRefundData->SetTotal_fee($this->totalFee);

            $wxRefundData->SetRefund_fee($this->refundFee);

            $wxRefundData->SetOp_user_id($this->opUserId);

            return $this->getRefundSign($wxRefundData);

        }

        private function getRefundSign($wxRefundData)
        {

            $wxRefund = \WxPayApi::refund($this->config, $wxRefundData);

            if ($wxRefund['return_code'] != 'SUCCESS' || $wxRefund['result_code'] != 'SUCCESS') {
                Log::record($wxRefund, 'error');
                Log::record('取消订单失败', 'error');
                throw new RefundException(['msg'=>$wxRefund['err_code_des']]);
            }

            $this->recordRefundOrder();
            //改变订单状态至退款
            $this->changeOrderState();

            return new SuccessMessage();

        }
        //记录退款
        private function recordRefundOrder()
        {
            $refund             = new RefundModel();
            $refund->order_id   = $this->orderID;
            $refund->refund_id  = $this->outRefundNo;
            $refund->refund_fee = $this->refundFee;
            $refund->save();
        }

        private function changeOrderState(){
            Order::where('id',$this->orderID)->update(['state'=>8]);
        }


    }